import axios from 'axios'
import qs from 'qs'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { local as storage } from '@/utils/storage' // 验权

const service = axios.create({
  baseURL:'https://czytest.cyzl.com',
  timeout: 15000,// 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['authorization'] = storage.get('token') // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  config.crossDomain = true;
  // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  return config
}, error => {
  return Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * code为 1033 时候重新登录
    */
    const res = response.data;
    if (res.code == 1033) {
      store.dispatch('FedLogOut').then(() => {
        location.reload()// 为了重新实例化vue-router对象 避免bug
      })
    } else {
      return response.data
    }
  },
  error => {
    alert(111)
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)
function apiAxios(method, url, params, contentTypeStr) {
  let httpDefault = {
    method: method,
    url: url,
    params: method === 'GET' || method === 'DELETE' ? params : '',
    data: method === 'POST' ? (contentTypeStr && contentTypeStr.indexOf('application/json') > -1 ? JSON.stringify(params) :qs.stringify(params)) : '',
    headers:{
      'Content-Type': contentTypeStr ? contentTypeStr :'application/x-www-form-urlencoded'      //改这里就好了
    },
  }
  return new Promise((resolve, reject) => {
    service(httpDefault)
    // 此处的.then属于axios
    .then((res) => {
      resolve(res)
    }).catch((response) => {
      reject(response)
    })
  })
}
export default {
    get: (url, params, contentTypeStr) => apiAxios('GET', url, params, contentTypeStr),
    post: (url, params, contentTypeStr) => apiAxios('POST', url, params, contentTypeStr),
}
